#include <stdlib.h>
#include <string.h>
#include <config.h>
#include <stm32f0xx.h>
#include <printk.h>
#include "device.h"
#include "stm32_spi.h"
#include "stm32_spi_bitbang.h"
#include "board.h"

#ifdef configUSING_SPI

static err_t configure(struct spi_device *device, struct spi_configuration *configuration);
static uint32_t xfer(struct spi_device *device, struct spi_message *message);

static struct spi_ops stm32_spi_ops =
{
    configure,
    xfer
};

void board_setup_spi(void)
{
#ifdef configUSING_SPI1
//    /*
//     * SPI1_MOSI: PA7
//     * SPI1_MISO: PA6
//     * SPI1_SCK : PA5
//     * CS0: PA4
//     */
    /*
     * SPI1_MOSI: PB5
     * SPI1_MISO: PB4
     * SPI1_SCK : PB3
     * CS0: PA15
     */
    /* register spi bus */
    {
        static struct stm32_spi_bus stm32_spi;
        GPIO_InitTypeDef GPIO_InitStructure;

        /* Enable GPIO clock */
        RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource3, GPIO_AF_0);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource4, GPIO_AF_0);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_0);

        GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        stm32_spi_register(SPI1, &stm32_spi, "spi1");
    }

    /* attach cs */
    {
        static struct spi_device spi_device;
        static struct stm32_spi_cs  spi_cs;

        GPIO_InitTypeDef GPIO_InitStructure;

        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;

        spi_cs.GPIOx = GPIOA;
        spi_cs.GPIO_Pin = GPIO_Pin_15;
        RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

        GPIO_InitStructure.GPIO_Pin = spi_cs.GPIO_Pin;
        GPIO_SetBits(spi_cs.GPIOx, spi_cs.GPIO_Pin);
        GPIO_Init(spi_cs.GPIOx, &GPIO_InitStructure);

        spi_bus_attach_device(&spi_device, "spid0", "spi1", (void *)&spi_cs);
    }
#endif /* USING_SPI1 */

#ifdef configUSING_SPI2
    /*
     * SPI1_MOSI: PB15
     * SPI1_MISO: PB14
     * SPI1_SCK : PB13
     * CS0: PB12
     */
    /* register spi bus */
    {
        static struct stm32_spi_bus stm32_spi;
        GPIO_InitTypeDef GPIO_InitStructure;

        /* Enable GPIO clock */
        RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_0);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_0);
        GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_0);

        GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
        GPIO_Init(GPIOB, &GPIO_InitStructure);

        stm32_spi_register(SPI2, &stm32_spi, "spi2");
    }

    /* attach cs */
    {
        static struct spi_device spi_device;
        static struct stm32_spi_cs  spi_cs;

        GPIO_InitTypeDef GPIO_InitStructure;

        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
        GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
        GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;

        spi_cs.GPIOx = GPIOB;
        spi_cs.GPIO_Pin = GPIO_Pin_12;
        RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);

        GPIO_InitStructure.GPIO_Pin = spi_cs.GPIO_Pin;
        GPIO_SetBits(spi_cs.GPIOx, spi_cs.GPIO_Pin);
        GPIO_Init(spi_cs.GPIOx, &GPIO_InitStructure);

        spi_bus_attach_device(&spi_device, "spid1", "spi2", (void *)&spi_cs);
    }
#endif /* USING_SPI2 */

#ifdef configUSING_SPI_BITBANG
    hw_spi_bitbang_init();
#endif
}

static uint16_t get_spi_BaudRatePrescaler(uint32_t max_hz)
{
    uint16_t SPI_BaudRatePrescaler;

    /* STM32F10x SPI MAX 18Mhz */
    if (max_hz >= SYS_CLOCK / 2 && SYS_CLOCK / 2 <= 18000000)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
    }
    else if (max_hz >= SYS_CLOCK / 4)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
    }
    else if (max_hz >= SYS_CLOCK / 8)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
    }
    else if (max_hz >= SYS_CLOCK / 16)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
    }
    else if (max_hz >= SYS_CLOCK / 32)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32;
    }
    else if (max_hz >= SYS_CLOCK / 64)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64;
    }
    else if (max_hz >= SYS_CLOCK / 128)
    {
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128;
    }
    else
    {
        /* min prescaler 256 */
        SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
    }

    return SPI_BaudRatePrescaler;
}

static err_t configure(struct spi_device *device, struct spi_configuration *configuration)
{
    struct stm32_spi_bus *stm32_spi_bus = (struct stm32_spi_bus *)device->bus;
    SPI_InitTypeDef SPI_InitStructure;

    SPI_StructInit(&SPI_InitStructure);

    /* data_width */
    if (configuration->data_width <= 8)
    {
        SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
    }
    else if (configuration->data_width <= 16)
    {
        SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
    }
    else
    {
        return -EIO;
    }
    /* baudrate */
    SPI_InitStructure.SPI_BaudRatePrescaler = get_spi_BaudRatePrescaler(configuration->max_hz);
    /* CPOL */
    if (configuration->mode & KN_SPI_CPOL)
    {
        SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
    }
    else
    {
        SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
    }
    /* CPHA */
    if (configuration->mode & KN_SPI_CPHA)
    {
        SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
    }
    else
    {
        SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
    }
    /* MSB or LSB */
    if (configuration->mode & SPI_MSB)
    {
        SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
    }
    else
    {
        SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_LSB;
    }
    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
    SPI_InitStructure.SPI_NSS  = SPI_NSS_Soft;

    /* init SPI */
    SPI_I2S_DeInit(stm32_spi_bus->SPI);
    SPI_Init(stm32_spi_bus->SPI, &SPI_InitStructure);

    SPI_RxFIFOThresholdConfig(stm32_spi_bus->SPI, SPI_RxFIFOThreshold_QF);
    /* Enable SPI_MASTER */
    SPI_Cmd(stm32_spi_bus->SPI, ENABLE);
    SPI_CalculateCRC(stm32_spi_bus->SPI, DISABLE);

    return 0;
};

#define SPI_WAIT_TIMEOUT    0xFFFF
static uint32_t xfer(struct spi_device *device, struct spi_message *message)
{
    struct stm32_spi_bus *stm32_spi_bus = (struct stm32_spi_bus *)device->bus;
    struct spi_configuration *config = &device->config;
    SPI_TypeDef *SPI = stm32_spi_bus->SPI;
    struct stm32_spi_cs *stm32_spi_cs = device->parent.user_data;
    uint32_t size = message->length, wait_time;

    /* take CS */
    if (message->cs_take)
    {
        GPIO_ResetBits(stm32_spi_cs->GPIOx, stm32_spi_cs->GPIO_Pin);
    }

    {
        if (config->data_width <= 8)
        {
            const uint8_t *send_ptr = message->send_buf;
            uint8_t *recv_ptr = message->recv_buf;

            while (size--)
            {
                uint8_t data = 0xFF;

                if (send_ptr != NULL)
                {
                    data = *send_ptr++;
                }

                //Wait until the transmit buffer is empty
                wait_time = 0;
                while (SPI_I2S_GetFlagStatus(SPI, SPI_I2S_FLAG_TXE) == RESET)
                {
                    if(SPI_WAIT_TIMEOUT == ++wait_time)
                    {
                        break;
                    }
                }
                // Send the byte
                SPI_SendData8(SPI, data);

                //Wait until a data is received
                wait_time = 0;
                while (SPI_I2S_GetFlagStatus(SPI, SPI_I2S_FLAG_RXNE) == RESET)
                {
                    if(SPI_WAIT_TIMEOUT == ++wait_time)
                    {
                        break;
                    }
                }
                // Get the received data
                data = SPI_ReceiveData8(SPI);

                if (recv_ptr != NULL)
                {
                    *recv_ptr++ = data;
                }
                board_feed_wdg();
            }
        }
        else if (config->data_width <= 16)
        {
            const uint16_t *send_ptr = message->send_buf;
            uint16_t *recv_ptr = message->recv_buf;

            while (size--)
            {
                uint16_t data = 0xFF;

                if (send_ptr != NULL)
                {
                    data = *send_ptr++;
                }

                //Wait until the transmit buffer is empty
                wait_time = 0;
                while (SPI_I2S_GetFlagStatus(SPI, SPI_I2S_FLAG_TXE) == RESET)
                {
                    if(SPI_WAIT_TIMEOUT == ++wait_time)
                    {
                        break;
                    }
                }
                // Send the byte
                SPI_I2S_SendData16(SPI, data);

                //Wait until a data is received
                wait_time = 0;
                while (SPI_I2S_GetFlagStatus(SPI, SPI_I2S_FLAG_RXNE) == RESET)
                {
                    if(SPI_WAIT_TIMEOUT == ++wait_time)
                    {
                        break;
                    }
                }
                // Get the received data
                data = SPI_I2S_ReceiveData16(SPI);

                if (recv_ptr != NULL)
                {
                    *recv_ptr++ = data;
                }
                board_feed_wdg();
            }
        }
    }

    /* release CS */
    if (message->cs_release)
    {
        GPIO_SetBits(stm32_spi_cs->GPIOx, stm32_spi_cs->GPIO_Pin);
    }

    return message->length;
};

/** \brief init and register stm32 spi bus.
 *
 * \param SPI: STM32 SPI, e.g: SPI1,SPI2,SPI3.
 * \param stm32_spi: stm32 spi bus struct.
 * \param spi_bus_name: spi bus name, e.g: "spi1"
 * \return
 *
 */
err_t stm32_spi_register(SPI_TypeDef *SPI,
                         struct stm32_spi_bus *stm32_spi,
                         const char *spi_bus_name)
{
    if (SPI == SPI1)
    {
        stm32_spi->SPI = SPI1;
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
    }
    else if (SPI == SPI2)
    {
        stm32_spi->SPI = SPI2;
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
    }
    else
    {
        return -ENOSYS;
    }

    return spi_bus_register(&stm32_spi->parent, spi_bus_name, &stm32_spi_ops);
}


#endif
